package cn.com.anypay.manager.controller.pay;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import org.springframework.web.client.RestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;

import cn.com.anypay.manager.common.utils.AlipaySignUtil;
import cn.com.anypay.manager.dto.config.payment.AlipayAppConfig;
import cn.com.anypay.manager.dto.config.payment.AlipayMerchantConfig;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.domain.AlipayTradeCreateModel;
import com.alipay.api.domain.ExtendParams;
import com.alipay.api.response.AlipayTradeCreateResponse;

@RestController
@RequestMapping("/api/isv/alipay")
public class IsvAlipayController {
    private static final Logger log = LoggerFactory.getLogger(IsvAlipayController.class);

    @Autowired
    @Qualifier("alipayIsvAppConfig")
    private AlipayAppConfig appConfig;

    @Autowired
    @Qualifier("alipaySubMerchantConfig")
    private AlipayMerchantConfig subMerchantConfig;

    @Autowired
    private RestTemplate restTemplate;

    // 创建特约商户支付订单
    @PostMapping("/v1/payments")
    public Map<String, Object> createPayment(@RequestBody Map<String, Object> params) {
        try {
            log.info("=== 创建特约商户支付订单开始 ===");
            log.info("请求参数: {}", params);

            // 1. 参数验证
            String orderNo = (String) params.get("orderNo");
            Double amount = ((Number) params.get("amount")).doubleValue();
            String description = (String) params.get("description");
            String userId = (String) params.get("userId");

            // 2. 生成订单号
            orderNo = String.format("ORDER_%d_%s",
                System.currentTimeMillis(),
                UUID.randomUUID().toString().replace("-", "").substring(0, 8)
            );

            if (orderNo == null || amount == null || userId == null) {
                log.warn("缺少必要参数3");
                return Map.of(
                    "code", -1,
                    "message", "缺少必要参数4"
                );
            }

            // 3. 验证金额
            if (amount <= 0 || amount > 50000) {
                log.warn("金额无效: {}", amount);
                return Map.of(
                    "code", -1,
                    "message", "金额无效，必须在0-50000之间"
                );
            }

            // 4. 初始化支付宝客户端
            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.setServerUrl(appConfig.getGateway());
            alipayConfig.setAppId(appConfig.getAppId());
            alipayConfig.setPrivateKey(appConfig.getPrivateKey());
            alipayConfig.setFormat("json");
            alipayConfig.setAlipayPublicKey(appConfig.getAlipayPublicKey());
            alipayConfig.setCharset("UTF-8");
            alipayConfig.setSignType("RSA2");
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);

            // 5. 构建请求模型
            AlipayTradeCreateModel model = new AlipayTradeCreateModel();
            model.setOutTradeNo(orderNo);
            model.setTotalAmount(String.format("%.2f", amount));
            model.setSubject(description);
            model.setBody(description);
            model.setBuyerId(userId);
            model.setProductCode("FACE_TO_FACE_PAYMENT");
            model.setTimeExpire(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date(System.currentTimeMillis() + 7200000)));

            // 添加服务商和特约商户信息
            ExtendParams extendParams = new ExtendParams();
            extendParams.setSysServiceProviderId(subMerchantConfig.getPid());
            model.setExtendParams(extendParams);

            // 6. 创建请求
            AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
            request.setBizModel(model);
            request.setNotifyUrl(appConfig.getNotifyUrl() + "/api/pay/notify/alipay-isv");
            request.putOtherTextParam("app_auth_token", subMerchantConfig.getAppAuthToken());

            // 7. 执行请求
            AlipayTradeCreateResponse response = alipayClient.execute(request);
            log.info("支付宝响应: {}", response.getBody());

            if (response.isSuccess()) {
                String tradeNo = response.getTradeNo();

                // 8. 生成支付参数
                Map<String, String> payParams = new HashMap<>();
                payParams.put("appId", appConfig.getAppId());
                payParams.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
                payParams.put("nonceStr", UUID.randomUUID().toString().replace("-", ""));
                payParams.put("tradeNo", tradeNo);
                payParams.put("signType", "RSA2");

                // 9. 生成签名
                String paySign = AlipaySignUtil.generateSign(payParams, appConfig.getPrivateKey());
                payParams.put("sign", paySign);

                return Map.of(
                    "code", 0,
                    "message", "success",
                    "data", Map.of(
                        "orderNo", orderNo,
                        "tradeNo", tradeNo,
                        "payParams", payParams
                    )
                );
            } else {
                String errorMsg = String.format("创建支付订单失败: %s - %s",
                    response.getSubCode(),
                    response.getSubMsg());
                log.error(errorMsg);
                return Map.of(
                    "code", -1,
                    "message", errorMsg
                );
            }
        } catch (Exception e) {
            log.error("创建特约商户支付订单失败: {}", e.getMessage(), e);
            return Map.of(
                "code", -1,
                "message", "创建特约商户支付订单失败: " + e.getMessage()
            );
        }
    }
}